package com.sc.highspeed.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.highspeed.controller.result.JsonResult;
import com.sc.highspeed.db.model.OrganizationModel;
import com.sc.highspeed.db.model.UserGroupModel;
import com.sc.highspeed.db.model.UserMenuModel;
import com.sc.highspeed.db.model.UserModel;
import com.sc.highspeed.service.OrganizationService;
import com.sc.highspeed.service.UserGroupService;
import com.sc.highspeed.service.UserMenuService;
import com.sc.highspeed.service.UserService;
import com.sc.highspeed.temp.OrgTemp;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.tools.ant.taskdefs.condition.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Admin on 2017/12/2.
 */
@Api(value = "机构管理接口", description = "机构管理接口")
@Controller
@RequestMapping("/orgManage")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserGroupService userGroupService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMenuService userMenuService;

    /**
     * 获取所有机构
     * @return
     */
    @RequestMapping(value = "/getOrgList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取所有机构",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public List<OrganizationModel> getOrganizationList() {
        return organizationService.getOrganizationList();
    }

    /**
     * 获取机构
     * @param name
     * @return
     */
    @RequestMapping(value = "/getOrg", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据机构名获取机构详情",httpMethod = "GET",
            response = JsonResult.class, notes = "")

    public JsonResult getOrganizationByName(@ApiParam(value = "机构名") @RequestParam String name) {
        List resultList = new ArrayList();

        OrganizationModel organizationModel = organizationService.getOrganizationByName(name);
        JsonResult result = new JsonResult();
        if (organizationModel != null) {
            resultList.add(organizationModel);
            resultList.add(userGroupService.getUserGroupListByOrg(name));
            resultList.add(userService.getUserListByOrg(name));
            result.setObject(resultList);
        } else {
            result.setCode(0);
            result.setStatus(true);
            result.setMsg("该机构不存在！");
        }
        return result;
    }

    @RequestMapping(value = "/getOrgById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "通过id获取机构详情",httpMethod = "GET",
            response = JsonResult.class, notes = "返回机构详情，机构下所有用户组以及机构下所有用户")

    public JsonResult getOrganizationById(@ApiParam(value = "id") @RequestParam int id) {
        List resultList = new ArrayList();
        OrganizationModel organizationModel = organizationService.getOrganizationById(id);
        String name = organizationModel.getName();
        JsonResult result = new JsonResult();
        if (organizationModel != null) {
            resultList.add(organizationModel);
            resultList.add(userGroupService.getUserGroupListByOrg(name));
            resultList.add(userService.getUserListByOrg(name));
            result.setObject(resultList);
        } else {
            result.setCode(0);
            result.setStatus(true);
            result.setMsg("该机构不存在！");
        }

        return result;
    }
    /**
     * 添加机构
     * @param map
     * @return
     */
    @RequestMapping(value = "/insertOrg", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新建机构",httpMethod = "POST",
            response = JsonResult.class, notes = "")

    public JsonResult insertOrganization(@ApiParam(value = "机构实体(organization)，管理员用户实体(user)，管理员权限数组(menus)") @RequestBody Map<String, Object> map) throws IOException {
        JsonResult result = new JsonResult();
        ObjectMapper mapper1 = new ObjectMapper();
        ObjectMapper mapper2 = new ObjectMapper();
        int code = 0;
        UserMenuModel userMenuModel = new UserMenuModel();
        String orgJson = mapper1.writeValueAsString(map.get("organization"));
        String userJson = mapper2.writeValueAsString(map.get("user"));
        OrganizationModel organizationModel = mapper1.readValue(orgJson, OrganizationModel.class);
        UserModel userModel = mapper2.readValue(userJson, UserModel.class);
        List<Integer> menus = (List<Integer>) map.get("menus");
        userModel.setType("管理员");
        if (userService.getUserByUsername(userModel.getUsername()) != null) {
            result.setCode(-1);
            result.setStatus(false);
            result.setMsg("改管理员用户名已存在！");
            return result;
        }

        if (organizationService.getOrganizationByName(organizationModel.getName()) == null) {
            code = organizationService.insertOrganization(organizationModel);
            if (code == 1) {
                if (userService.insertUser(userModel) == 1) {
                    result.setCode(1);
                    result.setStatus(true);
                    if (userGroupService.getUserGroupByName(userModel.getUserGroup()) == null) {
                        UserGroupModel userGroupModel = new UserGroupModel();
                        userGroupModel.setGroupName(userGroupModel.getGroupName());
                        userGroupModel.setOrganization(userGroupModel.getOrganization());
                        if (userGroupService.insertUserGroup(userGroupModel) == 1) {
                            result.setCode(1);
                            result.setStatus(true);
                        } else {
                            result.setCode(0);
                            result.setStatus(false);
                            result.setMsg("用户组创建失败！");
                        }
                    }
                    for (int menu : menus) {
                        userMenuModel.setUsername(userModel.getUsername());
                        userMenuModel.setMenuId(menu);
                        userMenuService.insertUserMenu(userMenuModel);
                    }
                } else {
                    result.setCode(0);
                    result.setStatus(false);
                    result.setMsg("管理员创建失败！");
                }
            } else {
                result.setCode(0);
                result.setStatus(false);
                result.setMsg("机构添加失败！");
            }
        } else {
            result.setCode(-1);
            result.setStatus(false);
            result.setMsg("该机构已存在！");
        }
        return result;
    }

    /**
     * 更新机构
     * @param organizationModel
     * @return
     */
    @RequestMapping(value = "/updateOrg", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "更新机构信息",httpMethod = "POST",
            response = JsonResult.class, notes = "")

    public JsonResult updateOrganization(@ApiParam(value = "机构实体") @RequestBody OrganizationModel organizationModel) throws IOException {
        JsonResult result = new JsonResult();
        String orgName = organizationService.getOrganizationById(organizationModel.getId()).getName();
        if (!organizationModel.getName().equals(orgName)) {
            for (UserModel userModel : userService.getUserListByOrg(orgName)) {
                userService.updateUserOrganization(userModel.getUsername(), organizationModel.getName());
            }
            List<OrganizationModel> organizationModels = organizationService.getOrganizationByParent(orgName);
            for (OrganizationModel organization : organizationModels) {
                organizationService.updateOrganizationParent(organization.getId(), organizationModel.getName());
            }

            for (UserGroupModel userGroupModel : userGroupService.getUserGroupListByOrg(orgName)) {
                userGroupService.updateOrg(userGroupModel.getId(), organizationModel.getName());
            }
        }

        int code = organizationService.updateOrganizationById(organizationModel);
        if (code == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("更新失败！");
        }

        return result;
    }

    /**
     * 删除机构
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleteOrg", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "批量删除机构",httpMethod = "GET",
            response = JsonResult.class, notes = "")

    public List<JsonResult> deleteOrganizationByNames(@ApiParam(value = "机构名数组(names)") @RequestBody Map<String, Object> map) {
        List<JsonResult> results = new ArrayList<JsonResult>();
        List<String> names = (ArrayList<String>)map.get("names");
        int code = 0;
        for (String name : names) {
            JsonResult result = new JsonResult();
            code = organizationService.deleteOrganizationByName(name);
            if (code == 1) {
                result.setCode(1);
                result.setStatus(true);
            } else {
                result.setCode(0);
                result.setStatus(false);
                result.setMsg("删除失败！");
            }
            results.add(result);
        }
        return results;
    }

//    /**
//     * 更新机构备注
//     * @param name
//     * @param remark
//     * @return
//     */
//    @RequestMapping(value = "/updateOrgRemark", method = RequestMethod.GET)
//    @ResponseBody
//    public JsonResult updateOrganizationRemarkByName(@RequestParam String name, @RequestParam String remark) {
//        JsonResult result = new JsonResult();
//        int code = organizationService.updateOrganizationRemarkByName(name, remark);
//        if (code == 1) {
//            result.setCode(1);
//            result.setStatus(true);
//        } else {
//            result.setCode(0);
//            result.setStatus(false);
//            result.setMsg("更新失败！");
//        }
//
//        return result;
//    }

//    /**
//     * 更新机构简介
//     * @param name
//     * @param intro
//     * @return
//     */
//    @RequestMapping(value = "/updateOrgIntro", method = RequestMethod.GET)
//    @ResponseBody
//    public JsonResult updateOrnizationIntroByName(@RequestParam String name, @RequestParam String intro) {
//        JsonResult result = new JsonResult();
//        int code = organizationService.updateOrganizationIntroByName(name, intro);
//        if (code == 1) {
//            result.setCode(1);
//            result.setStatus(true);
//        } else {
//            result.setCode(0);
//            result.setStatus(false);
//            result.setMsg("更新失败！");
//        }
//
//        return result;
//    }

//    @RequestMapping(value = "/updateOrgIsCheck", method = RequestMethod.GET)
//    @ResponseBody
//    public JsonResult updateOrganizationIsCheckByName(@RequestParam String name, @RequestParam String isCheck) {
//        JsonResult result = new JsonResult();
//        int code = organizationService.updateOrganizationIsCheckByName(name, isCheck);
//        if (code == 1) {
//            result.setCode(1);
//            result.setStatus(true);
//        } else {
//            result.setCode(0);
//            result.setStatus(false);
//            result.setMsg("审核失败！");
//        }
//        return result;
//    }

    @RequestMapping(value = "/getTemp", method = RequestMethod.GET)
    @ResponseBody
    public OrgTemp getTemp(@RequestParam String name) {
        OrgTemp orgTemp = new OrgTemp();
        OrganizationModel organizationModel = organizationService.getOrganizationByName(name);
        orgTemp.setName(name);
        orgTemp.setParentName(organizationModel.getParentName());
        orgTemp.setLevel(organizationModel.getLevel());
        return orgTemp;
    }

//    @RequestMapping("/getOrgListUnCheck")
//    @ResponseBody
//    public List<OrganizationModel> getOrgListUnCheck() {
//        return organizationService.getOrganizationListUnCheck();
//    }

}
